package org.tgcloud.group.service.manager.third;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.HttpClientUtil;
import org.tgcloud.group.core.ResultMessage;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.repository.MjBusinessPersonMapper;
import org.tgcloud.group.web.controller.dto.project.IntendedMedia.AppIntendedMediaProjectDTO;
import org.tgcloud.group.web.controller.dto.third.MJShopDictDTO;
import org.tgcloud.group.web.controller.dto.third.MJShopOrderDTO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhy
 * @Created: 2025-08-25-下午2:31
 * @Description:
 */
@Slf4j
@Service
public class MJShopThirdManageService {

    private static String thirdUrl = "https://mjoa.mejour.cn/admin-api";

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Autowired
    private MjBusinessPersonMapper businessPersonMapper;

    public APPResultMessage getThirdSysLabelList(String codes) {
        if (StringUtil.isBlank(codes)){
            return APPResultMessage.getSuccessMessage();
        }
        Map map = new HashMap();
        map.put("dictType", codes);
        String url = thirdUrl + "/trade/order/pageForOut";
        String msg = httpClientUtil.doGetMJShop(url, map);
        JSONObject info = JSON.parseObject(msg, new TypeReference<JSONObject>() {
        });
        log.error("获取爱省鲸的字典数据:" + msg);
        if (info.getInteger("code") == 0){
            JSONArray data = info.getJSONArray("data");
            List<MJShopDictDTO> list =new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                JSONObject item = data.getJSONObject(i);
                MJShopDictDTO dto = new MJShopDictDTO();
                dto.setLabel(item.getString("label"));
                dto.setValue(item.getString("value"));
                list.add(dto);
            }
            ResultMessage result = ResultMessage.builder().setList(list);
            APPResultMessage message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }else {
            return APPResultMessage.getErrorMessage(info.toString());
        }
    }

    public APPResultMessage getBusinessOrderList(int userId, String searchUserIds, String spuName, Long createStartTime, Long createEndTime,
                                                 Long orderStatus, Long refundStatus, Integer pageNum, Integer pageSize) {
        List<Integer> businessUserIdList = new ArrayList<>();
        if (StringUtil.isNotBlank(searchUserIds)){
            String[] split = searchUserIds.split(",");
            for (String s : split){
                businessUserIdList.add(Integer.valueOf(s));
            }
        }else {
            businessUserIdList.add(userId);
        }
        List<String> telephoneList = businessPersonMapper.selectListByUserIdList(businessUserIdList);
        String telephones = String.join(",", telephoneList);
        Map map = new HashMap();
        map.put("telNos", telephones);
        map.put("pageNo", pageNum);
        map.put("pageSize", pageSize);
        if (StringUtil.isNotBlank(spuName)){
            map.put("name", spuName);
        }
        if (createStartTime != null && createEndTime != null){
            String[] times = {
                    createStartTime.toString(),
                    createEndTime.toString()
            };
            map.put("orderTime", times);
        }
        if (orderStatus != null){
            map.put("status", orderStatus);
        }
        if (refundStatus != null){
            map.put("refundStatus", refundStatus);
        }
        String url = thirdUrl + "/trade/order/pageOderByPhone";
        String msg = httpClientUtil.doPostJsonMJShop(url, map);
        JSONObject info = JSON.parseObject(msg, new TypeReference<JSONObject>() {
        });
        if (info.getInteger("code") == 0){
            JSONObject data = info.getJSONObject("data");
            Integer total = data.getInteger("total");
            JSONArray list = data.getJSONArray("list");
            List<MJShopOrderDTO> orderList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                JSONObject item = list.getJSONObject(i);
                MJShopOrderDTO dto = new MJShopOrderDTO();
                dto.setName(item.getString("name"));
                dto.setOrderNo(item.getString("orderNo"));
                dto.setOrderTime(item.getObject("orderTime", Long.class));
                dto.setCount(item.getObject("productCount", Integer.class));
                dto.setPayPrice(item.getObject("payPrice", Integer.class));
                dto.setStatus(item.getObject("status", Integer.class));
                dto.setRefundStatus(item.getObject("refundStatus", Integer.class));
                orderList.add(dto);
            }
            PageInfo<MJShopOrderDTO> tables = new PageInfo<>(orderList);
            ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(calculateTotalPages(total, pageSize)).setCount(total);
            APPResultMessage<Object, AppIntendedMediaProjectDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }else {
            return APPResultMessage.getErrorMessage(info.toString());
        }
    }

    public APPResultMessage getBusinessOrderCount(int userId, String searchUserIds, String spuName, Long createStartTime, Long createEndTime,
                                                  Long orderStatus, Long refundStatus) {
        List<Integer> businessUserIdList = new ArrayList<>();
        if (StringUtil.isNotBlank(searchUserIds)){
            String[] split = searchUserIds.split(",");
            for (String s : split){
                businessUserIdList.add(Integer.valueOf(s));
            }
        }else {
            businessUserIdList.add(userId);
        }
        List<String> telephoneList = businessPersonMapper.selectListByUserIdList(businessUserIdList);
        String telephones = String.join(",", telephoneList);
        Map map = new HashMap();
        map.put("telNos", telephones);
        if (StringUtil.isNotBlank(spuName)){
            map.put("name", spuName);
        }
        if (createStartTime != null && createEndTime != null){
            String[] times = {
                    createStartTime.toString(),
                    createEndTime.toString()
            };
            map.put("orderTime", times);
        }
        if (orderStatus != null){
            map.put("status", orderStatus);
        }
        if (refundStatus != null){
            map.put("refundStatus", refundStatus);
        }
        String url = thirdUrl + "/trade/order/totalPrice";
        String msg = httpClientUtil.doPostJsonMJShop(url, map);
        JSONObject info = JSON.parseObject(msg, new TypeReference<JSONObject>() {
        });
        if (info.getInteger("code") == 0){
            Integer count = info.getInteger("data");
            ResultMessage result = ResultMessage.builder().setData(count);
            APPResultMessage message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }else {
            return APPResultMessage.getErrorMessage(info.toString());
        }
    }

    public static int calculateTotalPages(Integer total, Integer pageSize) {
        // 处理边界情况：避免空指针和除零异常
        if (pageSize == null || pageSize <= 0) {
            throw new IllegalArgumentException("pageSize必须是正整数");
        }
        if (total == null || total <= 0) {
            return 0; // 总数为0时，页数为0
        }
        // 核心公式：向上取整
        return (total + pageSize - 1) / pageSize;
    }

}
